<?php

namespace App\Services\Vote;

use App\Models\School\Position;
use App\Models\Vote\Vote;
use App\Models\Vote\VoteLog;
use App\Models\Member\Member;
use App\Services\Member\MemberService;
use App\Services\Com\StatisticsService;
use App\Services\Com\UtilService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class VoteService
{
    /**
     * 投票额外信息
     * @param value_arr 当前投票内容
     **/
    public static function extInfo(array $value_arr = [], $is_mtl = false){
        //发布者
        $publish_info = Member::with([
                'country'=>function($query){
                    $query->select(['uuid', 'name', 'mobile_prefix', 'nationalflag', 'code']);
                }
            ])
            ->where('uuid', $value_arr['member_uuid'])->first();
        
        $online = 0;
        // 在线状态,只有单个信息的才从这里查
        if($is_mtl == false){
            $user_onlines = MemberService::onlineUsersMtl([$value_arr['member_uuid']]);
            if(isset($user_onlines[$value_arr['member_uuid']])){
                $online = 1;
            }
        }
        
        //结束天数
        $is_over = strtotime($value_arr['end_time']) >= time() ? 0 : 1 ;
        $end_day = 0;
        if($is_over == 0){
            $end_day = ceil(intval( strtotime($value_arr['end_time']) - time() )/86400);
            $end_day = $end_day >= 30 ? 30 : $end_day;
        }
        //评论
        $comment_count = StatisticsService::get($value_arr['uuid'])['comment_num'];
        //参数量
        $where_cnt = [];
        $where_cnt[] = ['vote_uuid', '=', $value_arr['uuid']];
        $log_cnt = VoteLog::where($where_cnt)->count();

        $res['publish_info'] = $publish_info;
        $res['online'] = $online;
        $res['is_over'] = $is_over;
        $res['comment_count'] = intval($comment_count + $log_cnt);
        $res['end_day'] = $end_day;

        return $res;
    }

    public static function feedVoteInfo(array $where = [], $member_uuid = ''){
        
        $where[] = ['state', '=', 1];
        
        $value = Vote::where($where)->first();
        if(empty($value)){
            return null;
        }
        $value_arr = $value->toArray();

        $ext = self::extInfo($value_arr);

        $data['id']=$value_arr['id'];//投票id
        $data['uuid']=$value_arr['uuid'];//vote uuid
        $data['start_time']=$value_arr['start_time'];//投票开始时间
        $data['end_time']=$value_arr['end_time'];//投票结束时间
        $data['image']=$value_arr['bg_img'];//主图
        $data['title']=$value_arr['title'];//标题
        $data['description']=$value_arr['content'];//描述

        $data['username']=$value->member->nickname;//用户名
        $data['member_uuid']=$value->member->uuid;//创建者uuid
        $data['avatar']=$value->member->avatar_url;//用户头像
        $data['vote_type'] = $value_arr['vote_type'];//普通投票，选举，弹劾，就是：1，2，3

        $data['school_uuid']=$value_arr['school_uuid'];//学校uuid

        if($value_arr['vote_type'] == 2){
            $data['position_name']=$value->position->position ?? '';//职位名
            $data['position_uuid']=$value->position->uuid ?? '';//职位uuid
        }
        if($value_arr['vote_type'] == 3){
            $data['impeach_username']=$value->impeach->nickname ?? '';//被弹劾用户名
            $data['impeach_member_uuid']=$value->impeach->uuid ?? '';//被弹劾创建者uuid
            $data['impeach_avatar']=$value->impeach->avatar_url ?? '';//被弹劾用户头像    
            $data['position_name']=$value->position->position ?? '';//职位名
            $data['position_uuid']=$value->position->uuid ?? '';//职位uuid
        }

        //阵营列表
        $item = [];
        foreach ($value->item as $key_l => $value_l) {
            $where_cnt = [];
            $where_cnt[] = ['vote_uuid', '=', $value['uuid']];
            $where_cnt[] = ['camp', '=', $value_l['camp']];
            $log_cnt = VoteLog::where($where_cnt)->count();
            $item[$key_l]['id'] = $value_l['id'];
            $item[$key_l]['uuid'] = $value_l['uuid'];
            $item[$key_l]['camp'] = $value_l['camp'];
            $item[$key_l]['name'] = $value_l['name'];
            $item[$key_l]['sum'] = $log_cnt;
        }

        $data['camp']=$item;

        //当前用户对此投票的状态
        $where_member[] = ['vote_uuid', '=', $value['uuid']];
        $where_member[] = ['member_uuid', '=', $member_uuid];
        $m_log_res = VoteLog::where($where_member)->first();
        $data['join_camp']=$m_log_res->camp ?? null;//已经支持的阵营 id

        $data['publish_info']  = $ext['publish_info'];//有认证， 有国家
        $data['comment_count'] = $ext['comment_count'];//评论量+参与人
        $data['online'] = $ext['online'];//在线状态
        $data['end_day'] = $ext['end_day'];//投票多久结束
        $data['is_over'] = $ext['is_over'];//是否已结束 0未结束 1已经结束

        return $data;
    }

    /**
     *
     * position: 显示位置
     *  all_feeds 全域  
     *  member_feeds 个人圈子
     *  school 学校圈子
     * 
     * $where['vote_type']
     * $where['show_member_uuid']
     *  
     **/
    public static function listInFeeds(int $page = 1, string $member_uuid = '', int $limit = 6, string $position = 'member_feeds', 
        string $school_uuid = '', array $where = [])
    {
        // DB::connection()->enableQueryLog();

        $res = $res_page = null;
        $model = Vote::where('vote.state', '<>', 0);
        
        
        //参与类型 0:所有，1:我发布的，2:我参与的，
        if(isset($where['join_type']) && !empty($where['join_type'])){
            if( $where['join_type'] == 1){
                $model->where('vote.member_uuid', '=', $member_uuid);
            }elseif($where['join_type'] == 2){
                $model->join('vote_log',function($join) use ($member_uuid){
                    $join->on('vote_log.vote_uuid', '=', 'vote.uuid')->where('vote_log.member_uuid','=',$member_uuid);
                });
            }
        }
        //进行类型 1:进行中，2:已经结束
        if(isset($where['ing_type']) && !empty($where['ing_type'])){
            if($where['ing_type'] == 1){
                $model->where('vote.end_time', '>',  date('Y-m-d H:i:s',time()));
            }elseif($where['ing_type'] == 2){
                $model->where('vote.end_time', '<',  date('Y-m-d H:i:s',time()));
            }
        }

        //没有类型就默认是普通投票
        if(isset($where['vote_type'])){
            $model->whereIn('vote.vote_type',explode(',', $where['vote_type']));
        }else{
            $model->whereIn('vote.vote_type',[1]);
        }

        //排序
        if($position == 'hot' ){//全域信息热门
            $model->orderBy('vote.is_recommend', 'desc');
            $model->orderBy('vote.recommend_update_time', 'desc');
        }

        //最新发布的在前端，然后即将结束的也在前面，所以把所有把已经结束的取一个大数,自动排去后面
        $model->orderByRaw('case when vote.end_time < now() then  0 else vote.id end desc, vote.id desc');
        $model->orderBy('vote.state', 'asc');
        $model->orderBy('vote.id', 'desc');

        $res = [];
        //显示位置
        if($position == 'member_feeds'){//显示同步的

            $model->where('posts_view_by_user.member_uuid','=', $where['show_member_uuid']);
            $model->join('posts_view_by_user', 'posts_view_by_user.post_uuid', '=', 'vote.uuid')
            ->where('posts_view_by_user.type', 'vote')
            ->select('vote.*')
            ->groupBy('posts_view_by_user.post_uuid');
            $res = $res_page_obj = $model->paginate($limit,'*','page', $page);
            $res_page = $res_page_obj->toArray();
            unset($res_page['data']);
        }elseif($position == 'hot' ){//全域信息热门
            //置顶
            $res = $res_page_obj = $model->paginate($limit,'vote.*','page', 1);
            $res_page = $res_page_obj->toArray();
            unset($res_page['data']);
        }elseif($position == 'school_feeds'){//学校
            
            if(!empty($school_uuid)){
                $model->where('vote.school_uuid','=', $school_uuid);
            }
            $res = $res_page_obj = $model->paginate($limit,'vote.*','page', $page);
            $res_page = $res_page_obj->toArray();
            unset($res_page['data']);
        }elseif($position == 'all_feeds'){//全域广场
            
            //显示全部的
            $res = $res_page_obj = $model->paginate($limit,'vote.*','page', $page);
            $res_page = $res_page_obj->toArray();
            unset($res_page['data']);
        }

// $log = DB::getQueryLog();
// var_dump([ $log]);
// die;

        $data = self::dataHandel($res, $member_uuid);
        $res_arr['page_info'] = $res_page;
        $res_arr['data'] = $data ? $data : null;

        return $res_arr;
    }

    /**
     * 只返回一次，不用管分页
     * 显示位置：position 学校流里 feeds,  选举弹劾列表里 list
     *  
     **/
    public static function electionInFeeds(int $page = 1, string $member_uuid = '', int $limit = 6, string $position = 'feeds', string $school_uuid = '')
    {
        $res_page = null;
        $limit_1 = 3;
        //选举的
        $model = Vote::where('vote.state', 1)->whereIn('vote.vote_type',[2]);
        if(!empty($school_uuid)){
           $model->where('school_uuid', '=', $school_uuid);
        }
        $model->orderBy('vote.id', 'desc');
        $res1 = $res_page_obj = $model->paginate($limit_1);
        $res_page = $res_page_obj->toArray();
        $data1 = self::dataHandel($res1, $member_uuid);

        //弹劾的
        $limit_2 = $limit-$res_page['total'];
        $model = Vote::where('vote.state', 1)->whereIn('vote.vote_type',[3]);
        if(!empty($school_uuid)){
           $model->where('school_uuid', '=', $school_uuid);
        }
        $model->orderBy('vote.id', 'desc');
        $res2 = $res_page_obj = $model->paginate($limit_2);
        $data2 = self::dataHandel($res2, $member_uuid);

        //合并数据
        if(!empty($data1) && !empty($data2)){
            $data = array_merge($data1, $data2);
        }elseif(!empty($data1)){
            $data = $data1;
        }elseif(!empty($data2)){
            $data = $data2;
        }
        
        $res_arr['data'] = $data ?? null;

        return $res_arr;
    }

    //数据处理
    protected static function dataHandel($res, $member_uuid){
        $data = null;
        $user_ids = [];
        foreach ($res as $key => $value) {
            $user_ids[] = $value->member->uuid;
        }
        
        $user_onlines = MemberService::onlineUsersMtl($user_ids);
        
        foreach ($res as $key => $value) {

            $ext = self::extInfo($value->toArray(), true);

            $data[$key]['id']=$value['id'];//投票id
            $data[$key]['vote_type']=$value['vote_type'];//投票类型
            $data[$key]['uuid']=$value['uuid'];//vote uuid
            $data[$key]['start_time']=date('Y-m-d H:i:s', strtotime($value['start_time']));//投票开始时间
            $data[$key]['end_time']=date('Y-m-d H:i:s', strtotime($value['end_time']));//投票结束时间
            $data[$key]['image']=$value['bg_img'];//主图
            $data[$key]['title']=$value['title'];//标题
            $data[$key]['vote_type']=$value['vote_type'];//类型
            $data[$key]['description']=$value['content'];//描述

            $data[$key]['username']=$value->member->nickname;//用户名
            $data[$key]['member_uuid']=$value->member->uuid;//创建者uuid
            $data[$key]['avatar']=$value->member->avatar_url;//用户头像

            $data[$key]['school_uuid']=$value['school_uuid'];//学校uuid
            if($value['vote_type'] == 2){
                $data[$key]['position_name']=$value->position->position ?? '';//职位名
                $data[$key]['position_uuid']=$value->position->uuid ?? '';//职位uuid
            }
            if($value['vote_type'] == 3){
                $data[$key]['impeach_username']=$value->impeach->nickname ?? '';//被弹劾用户名
                $data[$key]['impeach_member_uuid']=$value->impeach->uuid ?? '';//被弹劾创建者uuid
                $data[$key]['impeach_avatar']=$value->impeach->avatar_url ?? '';//被弹劾用户头像    
                $data[$key]['position_name']=$value->position->position ?? '';//职位名
                $data[$key]['position_uuid']=$value->position->uuid ?? '';//职位uuid
            }

            $item = null;
            //阵营列表
            foreach ($value->item as $key_l => $value_l) {
                $where_cnt = null;
                $where_cnt[] = ['vote_uuid', '=', $value['uuid']];
                $where_cnt[] = ['camp', '=', $value_l['camp']];
                $log_cnt = VoteLog::where($where_cnt)->count();
                
                $item[$key_l]['id'] = $value_l['id'];
                $item[$key_l]['uuid'] = $value_l['uuid'];
                $item[$key_l]['camp'] = $value_l['camp'];
                $item[$key_l]['name'] = $value_l['name'];
                $item[$key_l]['sum'] = $log_cnt;
            }

            $data[$key]['camp']=$item;
            $where_member = [];
            $where_member[] = ['vote_uuid', '=', $value['uuid']];
            $where_member[] = ['member_uuid', '=', $member_uuid];
            $m_log_res = VoteLog::where($where_member)->first();

            $data[$key]['join_camp'] = $m_log_res->camp ?? null;//已经支持的阵营 id

            $data[$key]['publish_info']  = $ext['publish_info'];//有认证， 有国家
            $data[$key]['comment_count'] = $ext['comment_count'];//评论量
            $data[$key]['online']  = isset($user_onlines[$value->member->uuid]) ? 1 : 0;//在线状态
            $data[$key]['end_day'] = $ext['end_day'];//投票多久结束
            $data[$key]['is_over'] = $ext['is_over'];//是否已结束 0未结束 1已经结束
        }
        return $data;
    }


}